package com.magiccompass.alipay.barcode.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.magiccompass.alipay.barcode.controller.AlipayBarcodePaymentController;
import com.magiccompass.alipay.barcode.entity.AppDictionary;
import com.magiccompass.alipay.barcode.service.SystemService;

@Component
public class DicInit implements ApplicationListener<ContextRefreshedEvent> {
	private static Logger logger = LogManager.getLogger(AlipayBarcodePaymentController.class.getName());
	
	@Resource(name="systemService")
	private SystemService systemService;
	
	public static HashMap<String, List<String[]>> SYSTEM_CODE_MAP = new HashMap<String, List<String[]>>();
	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		logger.info("ContextRefreshedEvent Received in DicInit");
		makeSystemCode();
	}
	public void makeSystemCode() {
		SYSTEM_CODE_MAP = new HashMap<String, List<String[]>>();
		List<AppDictionary> tempList = systemService.getAppDictionaryDBList();
		//List<TSSystemCode> tempList = makeDummyTSSystemCode();
		String codeKey;
		List<String[]> codeAndValueList;
        for(AppDictionary aRow:tempList){
    		codeKey = aRow.getTableName().toUpperCase()+"."+aRow.getColumnName().toUpperCase();
    		if(SYSTEM_CODE_MAP.containsKey(codeKey)){
    			codeAndValueList = SYSTEM_CODE_MAP.get(codeKey);
    			codeAndValueList.add(new String[]{aRow.getColumnCode(),aRow.getColumnValue()});
    			SYSTEM_CODE_MAP.put(codeKey, codeAndValueList);
    		}else{
    			codeAndValueList = new ArrayList<String[]>();
    			codeAndValueList.add(new String[]{aRow.getColumnCode(),aRow.getColumnValue()});
        		SYSTEM_CODE_MAP.put(codeKey, codeAndValueList);
    		}
        }
	}
	
	public static String getSystemCode(String tableName, String columnName, String columnCode) {
    	//printSystemCodeMap();
    	String returnStr = "unknown";
        String codeKey = tableName.toUpperCase() + "." + columnName.toUpperCase();        
        if (SYSTEM_CODE_MAP.containsKey(codeKey)) {
        	List<String[]> tempCodeValueList = SYSTEM_CODE_MAP.get(codeKey);
        	for(String[] tempCodeAndValue:tempCodeValueList){
        		if(tempCodeAndValue[0].equals(columnCode)){
        			returnStr = tempCodeAndValue[1];
        			break;
        		}
        	}
        } else {
        	returnStr = "unknown";
        }
        return returnStr;
    }
}
